package org.apache.commons.digester;

import org.xml.sax.Attributes;

/**
 * <p>Rule implementation that saves a parameter for use by a surrounding
 * <code>CallMethodRule<code>.</p>
 * <p/>
 * <p>This parameter may be:
 * <ul>
 * <li>an arbitrary Object defined programatically, assigned when the element
 * pattern associated with the Rule is matched. See
 *
 * @author andrew
 */

public class PropertyParamRule extends Rule {

    public PropertyParamRule(int paramIndex) {
        this(paramIndex, null);
    }

    /**
     * Construct a "call parameter" rule that will save the given Object as
     * the parameter value.
     */

    public PropertyParamRule(int paramIndex, String keyName) {
        this.paramIndex = paramIndex;
        this.keyName = keyName;
    }

    /**
     * The zero-relative index of the parameter we are saving.
     */
    protected int paramIndex = 0;
    private String keyName;

    /**
     * Process the start of this element.
     *
     * @param attributes The attribute list for this element
     */
    public void begin(String namespace, String name,
                      Attributes attributes) throws Exception {
        Object parameters[] = (Object[]) digester.peekParams();

        if (keyName != null) {
            parameters[paramIndex] = keyName;
        } else {
            parameters[paramIndex] = name;
        }
    }

    /**
     * Render a printable version of this Rule.
     */
    public String toString() {
        StringBuffer sb = new StringBuffer("PropertyParamRule[");
        sb.append("paramIndex=");
        sb.append(paramIndex);
        sb.append("]");
        return (sb.toString());
    }
}
